package com.bjpowernode.payment01.web.service.impl;

import com.bjpowernode.payment01.db.domain.SimpleOrder;
import com.bjpowernode.payment01.db.mapper.SimpleOrderMapper;
import com.bjpowernode.payment01.web.models.dto.NoticeResultDto;
import com.bjpowernode.payment01.web.models.dto.PaymentDto;
import com.bjpowernode.payment01.web.models.form.GoodsForm;
import com.bjpowernode.payment01.web.models.form.NoticeForm;
import com.bjpowernode.payment01.web.service.PaymentService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class PaymentServiceImpl implements PaymentService {
    @Resource
    private SimpleOrderMapper orderMapper;
    @Override
    public PaymentDto generateParamSaveOrder(GoodsForm goodsForm) {
        //1.生成快钱需要的 接口参数值
        PaymentDto paymentDto = new PaymentDto("1001214035601","http://localhost:8080/notice/kq","User123@163.com",goodsForm);
        //2.保存记录到数据库
        SimpleOrder order = new SimpleOrder();
        order.setOrderNo(paymentDto.getOrderId());
        order.setUid(goodsForm.getPayerId());
        order.setPayTime(new Date());
        order.setPayMoney(goodsForm.getOrderMoney());
        order.setStatus(0);
        order.setRemark("快钱支付");
        order.setGoodsReplId("0");
        orderMapper.insert(order);
        return paymentDto;
    }

    @Override
    public NoticeResultDto handleNotice(NoticeForm noticeForm) {
        String pageUrl = "http://localhost:8080/show.html";
        NoticeResultDto noticeResultDto = new NoticeResultDto();
        //1.查询订单是否存在
        SimpleOrder order = orderMapper.selectByOrderIdForUpdate(noticeForm.getOrderId());
        if(order==null){
            return new NoticeResultDto("NONE",pageUrl);
        }
        //2.订单存在,判断订单是否处理过
        if(0!=order.getStatus()){
            return new NoticeResultDto("HANDLED",pageUrl);
        }
        //3.判断支付结果 10成功,11失败,更新订单记录
        int rows =0;
        if("10".equals(noticeForm.getPayResult())){
            rows = orderMapper.updateStatus(order.getId(),1);
            if( rows > 0){
                return new NoticeResultDto("PAY_SUCC",pageUrl);
            } else {
                return new NoticeResultDto("FAIL",pageUrl);
            }
        } else {
            rows = orderMapper.updateStatus(order.getId(),3);
            if( rows > 0 ){
                return new NoticeResultDto("PAY_FAIL",pageUrl);
            } else {
                return new NoticeResultDto("FAIL",pageUrl);
            }
        }
    }
}
